#include "PluginManagement.h"

#include <algorithm>

PluginManagement::PluginManagement() = default;

PluginManagement::~PluginManagement() = default;

bool PluginManagement::RegisterPlugin()
{
    KS_printK("--------------------- RegisterPlugin\n");
    // plugin目录下所有dll都将进行注册
    KSError error = KS_loadLibraryKernel(&plugin_info_[0].handle, "plugin/PluginDemo.dll", nullptr, nullptr, KSF_KERNEL_EXEC);
    if (error != KS_OK)
    {
        KS_printK("KS_loadLibraryKernel plugin failed!\n");
        return false;
    }

    error = KS_loadLibraryKernel(&plugin_info_[1].handle, "plugin/PluginDemo2.dll", nullptr, nullptr, KSF_KERNEL_EXEC);
    if (error != KS_OK)
    {
        KS_printK("KS_loadLibraryKernel plugin failed!\n");
        return false;
    }

    return true;
}

bool PluginManagement::UnRegisterPlugin() const
{
    // 内核资源释放
    const bool ret = std::ranges::all_of(plugin_info_, [](auto info) { return KS_freeKernel(info.handle) == KS_OK; });
    return ret;
}

KSHandle PluginManagement::GetPlugin(const char *chr) const
{
    for (const auto &plugin_info: plugin_info_)
    {
        if (KSRTL_strcmp(chr, plugin_info.name))
        {
            return plugin_info.handle;
        }
    }

    return 0;
}
